# -*-coding:utf-8 -*-

"""
# File       : AutoExpireTokenUtils.py
# Time       ：2022/8/17 下午11:49
# Author     ：puppet
# version    ：python 3.8.1
# Description：
"""

import pytz
from rest_framework.authentication import SessionAuthentication
from django.utils.translation import ugettext_lazy as _
from django.core.cache import cache
import datetime
from rest_framework.authentication import BaseAuthentication, TokenAuthentication
from rest_framework import exceptions
from rest_framework.authtoken.models import Token
from rest_framework import HTTP_HEADER_ENCODING


# 获取请求头里的token信息
# def get_authorization_header(request):
#     """
#     Return request's 'Authorization:' header, as a bytestring.
#
#     Hide some test client ickyness where the header can be unicode.
#     """
#     auth = request.META.get('HTTP_AUTHORIZATION_TOKEN', b'')
#     print("get_authorization_header.auth", auth)
#     if isinstance(auth, type('')):
#         # Work around django test client oddness
#         auth = auth.encode(HTTP_HEADER_ENCODING)
#     return auth


# 自定义的ExpiringTokenAuthentication认证方式
class ExpiringTokenAuthentication(BaseAuthentication):
    pass
    # model = Token
    #
    # def authenticate(self, request):
    #     auth = get_authorization_header(request)
    #     print("1,ExpiringTokenAuthentication:", auth)
    #     if not auth:
    #         return None
    #     try:
    #         token = auth.decode()
    #     except UnicodeError:
    #         msg = _('Invalid token header. Token string should not contain invalid characters.')
    #         raise exceptions.AuthenticationFailed(msg)
    #     return self.authenticate_credentials(token)
    #
    # def authenticate_credentials(self, key):
    #     # 增加了缓存机制
    #     # 首先先从缓存中查找
    #     token_cache = 'token_' + key
    #     # cache_user = cache.get(token_cache)
    #     # if cache_user:
    #     #     return cache_user.user, cache_user  # 首先查看token是否在缓存中，若存在，直接返回用户
    #     try:
    #         # token = self.model.objects.get(key=key[6:])
    #         token = self.model.objects.get(key=key)
    #
    #     except self.model.DoesNotExist:
    #         raise exceptions.AuthenticationFailed('认证失败')
    #
    #     if not token.user.is_active:
    #         raise exceptions.AuthenticationFailed('用户被禁止')
    #
    #     utc_now = datetime.datetime.utcnow()
    #     # 设定存活时间 14天
    #     if 14 < (utc_now.replace(tzinfo=pytz.timezone("UTC")) - token.created.replace(tzinfo=pytz.timezone("UTC"))).days:
    #         raise exceptions.AuthenticationFailed('认证信息过期')
    #     #
    #     # if token:
    #     #     token_cache = 'token_' + key
    #     #     cache.set(token_cache, token, 24 * 7 * 60 * 60)  # 添加 token_xxx 到缓存
    #     print("token.user:{}, token:{}".format(token.user, token))
    #     return token.user, token
    #
    # def authenticate_header(self, request):
    #     return 'Token'
